package com.i72.penetrate.init;

import com.i72.basic.consts.Consts;
import com.i72.basic.context.GlobalContext;
import com.i72.penetrate.rpc.RPCTarget;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.BeanFactoryAware;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.*;
import org.springframework.core.Ordered;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

@Component
public class RPCInit implements BeanFactoryAware,EnvironmentAware,Ordered{


    @Autowired
    private RPCTarget rpcTarget;


    private Environment environment;
    private BeanFactory factory;
    private String [] packages = null;

    @Override
    public void setEnvironment(Environment e) {

        this.environment = e;

        String subservice = GlobalContext.getSubscribelist();
        if(!StringUtils.isEmpty(subservice)){
            List<String> subscribeList =  Arrays.asList(subservice.split(","));

            List<String> packageList = new ArrayList<>();
            subscribeList.forEach(i->{
                packageList.add(Consts.SANC_BASE_PACKAGE+"."+i);
            });

            packages = new String[packageList.size()];

            packages = packageList.toArray(packages);

        }else{
            //packages = new String[]{this.getClass().getName().toString().split("\\.")[0]};

            //packages = new String[]{Consts.SANC_BASE_PACKAGE};

        }

        if(packages!=null) {
            rpcTarget.initProxy(factory, packages);
        }
    }

    @Override
    public void setBeanFactory(BeanFactory beanFactory) throws BeansException {


        this.factory = beanFactory;

    }

    @Override
    public int getOrder() {
        return Ordered.HIGHEST_PRECEDENCE+2;
    }
}


